package ee.maoinvest.backend.model.dao.postgresqlimplementations;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import ee.maoinvest.backend.database.ConnectionManager;
import ee.maoinvest.backend.model.dao.RegularReadingOfChildElectricityMeterDAO;
import ee.maoinvest.backend.model.data.RegularReadingOfChildElectricityMeter;

public class RegularReadingOfChildElectricityMeterDAOPostgresqlImpl implements RegularReadingOfChildElectricityMeterDAO
{
	Logger logger = Logger.getLogger(RegularReadingOfChildElectricityMeterDAOPostgresqlImpl.class);
	Connection dbConnection;
	String sql;
	PreparedStatement preparedStatement;
	Statement statement;
	ResultSet resultSet;
	private final int WARNING_NO_ROWS_AFFECTED = 0;
	private int rowsAffected;
	
	public RegularReadingOfChildElectricityMeterDAOPostgresqlImpl(Connection dbConnection)
	{
		this.dbConnection = dbConnection;
	}
	
//-----------------START OF BASIC CRUD-----------------------------------
	@Override
	public int insertRegularReadingOfChildElectricityMeter(
			RegularReadingOfChildElectricityMeter regularReadingOfChildElectricityMeter) 
	{
		resultSet = null;
		rowsAffected = WARNING_NO_ROWS_AFFECTED;
		sql = "INSERT INTO Regular_readings_of_child_electricity_meter " + 
				"(regularReadingOfParentElectricityMeterFK, childElectricityMeterFK, dateChildElectricityMeterReadingWasTaken, " + 
				"childElectricityMeterDaytimeReading, childElectricityMeterNightTimeReading, childElectricityMeterReactivePowerReading) " + 
				"VALUES " + 
				"(?, ?, ?, " + 
				"?, ?, ?);";
		
		try 
		{
			preparedStatement = dbConnection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
			
			preparedStatement.setInt		(	1, regularReadingOfChildElectricityMeter.getRegularReadingOfParentElectricityMeterFK());
			preparedStatement.setInt		(	2, regularReadingOfChildElectricityMeter.getChildElectricityMeterFK());
			preparedStatement.setDate		(	3, regularReadingOfChildElectricityMeter.getDateChildElectricityMeterReadingWasTaken());
			preparedStatement.setBigDecimal	(	4, regularReadingOfChildElectricityMeter.getChildElectricityMeterDaytimeReading());
			preparedStatement.setBigDecimal	(	5, regularReadingOfChildElectricityMeter.getChildElectricityMeterNightTimeReading());
			preparedStatement.setObject		(	6, regularReadingOfChildElectricityMeter.getChildElectricityMeterReactivePowerReading(), Types.NUMERIC);

			logger.info(preparedStatement.toString());
			rowsAffected = preparedStatement.executeUpdate();
			
			if (rowsAffected == 1)
			{
				resultSet = preparedStatement.getGeneratedKeys();
				resultSet.next(); //answer consist only 1 row, so move the cursor just once to start to process the result
				int newId = resultSet.getInt(1); // 1, because identifiers are held in the first column 
				regularReadingOfChildElectricityMeter.setRegularReadingOfChildElectricityMeterID(newId);
				return rowsAffected;
			}
			else
			{
				System.out.println("No rows affected!");
				logger.info("Unsuccessful insertion to a database: " + preparedStatement.toString());
				return WARNING_NO_ROWS_AFFECTED;
			}
		}
		catch (Exception e) 
		{
			e.printStackTrace();
			return WARNING_NO_ROWS_AFFECTED;
		}
		finally
		{
			ConnectionManager.getInstance().closeStatement(preparedStatement);
			ConnectionManager.getInstance().closeResultSet(resultSet);
		}
	}

	@Override
	public RegularReadingOfChildElectricityMeter getRegularReadingOfChildElectricityMeterByID(
			int regularReadingOfChildElectricityMeterID) 
	{
		resultSet = null;
		RegularReadingOfChildElectricityMeter regularReadingOfChildElectricityMeterRetrieved = null;
		sql = "SELECT * FROM Regular_readings_of_child_electricity_meter WHERE regularReadingOfChildElectricityMeterID = ?;";
		
		try 
		{
			preparedStatement = dbConnection.prepareStatement(
						sql,
						ResultSet.TYPE_SCROLL_INSENSITIVE,
						ResultSet.CONCUR_READ_ONLY
					);
			//filling the placeholders 
			preparedStatement.setInt(1, regularReadingOfChildElectricityMeterID);
			logger.info(preparedStatement.toString());
			resultSet = preparedStatement.executeQuery();
			//place the cursor at the beginning of a received data set (so it can start to read and process data)
			resultSet.beforeFirst();
			
			if (resultSet.next())
			{
				regularReadingOfChildElectricityMeterRetrieved = new RegularReadingOfChildElectricityMeter();
				regularReadingOfChildElectricityMeterRetrieved.setRegularReadingOfChildElectricityMeterID(resultSet.getInt("regularReadingOfChildElectricityMeterID"));
				regularReadingOfChildElectricityMeterRetrieved.setRegularReadingOfParentElectricityMeterFK(resultSet.getInt("regularReadingOfParentElectricityMeterFK"));
				regularReadingOfChildElectricityMeterRetrieved.setChildElectricityMeterFK(resultSet.getInt("childElectricityMeterFK"));
				regularReadingOfChildElectricityMeterRetrieved.setDateChildElectricityMeterReadingWasTaken(resultSet.getDate("dateChildElectricityMeterReadingWasTaken"));
				regularReadingOfChildElectricityMeterRetrieved.setChildElectricityMeterDaytimeReading(resultSet.getBigDecimal("childElectricityMeterDaytimeReading"));
				regularReadingOfChildElectricityMeterRetrieved.setChildElectricityMeterNightTimeReading(resultSet.getBigDecimal("childElectricityMeterNightTimeReading"));
				regularReadingOfChildElectricityMeterRetrieved.setChildElectricityMeterReactivePowerReading((BigDecimal) resultSet.getObject("childElectricityMeterReactivePowerReading"));
			}
		}
		catch (SQLException e) 
		{
			logger.error(e.getMessage());
		}
		finally
		{
			ConnectionManager.getInstance().closeStatement(preparedStatement);
			ConnectionManager.getInstance().closeResultSet(resultSet);
		}
		
		return regularReadingOfChildElectricityMeterRetrieved;
	}

	@Override
	public int updateRegularReadingOfChildElectricityMeter(
			RegularReadingOfChildElectricityMeter regularReadingOfChildElectricityMeter) 
	{
		resultSet = null;
		rowsAffected = WARNING_NO_ROWS_AFFECTED;
		sql = "UPDATE Regular_readings_of_child_electricity_meter " + 
				"SET regularReadingOfParentElectricityMeterFK = ?, childElectricityMeterFK = ?, dateChildElectricityMeterReadingWasTaken = ?, " + 
				"childElectricityMeterDaytimeReading = ?, childElectricityMeterNightTimeReading = ?, childElectricityMeterReactivePowerReading = ? " + 
				"WHERE regularReadingOfChildElectricityMeterID = ?;";
		
		try 
		{
			preparedStatement = dbConnection.prepareStatement(sql);
			
			preparedStatement.setInt		(	1, regularReadingOfChildElectricityMeter.getRegularReadingOfParentElectricityMeterFK());
			preparedStatement.setInt		(	2, regularReadingOfChildElectricityMeter.getChildElectricityMeterFK());
			preparedStatement.setDate		(	3, regularReadingOfChildElectricityMeter.getDateChildElectricityMeterReadingWasTaken());
			preparedStatement.setBigDecimal	(	4, regularReadingOfChildElectricityMeter.getChildElectricityMeterDaytimeReading());
			preparedStatement.setBigDecimal	(	5, regularReadingOfChildElectricityMeter.getChildElectricityMeterNightTimeReading());
			preparedStatement.setObject		(	6, regularReadingOfChildElectricityMeter.getChildElectricityMeterReactivePowerReading(), Types.NUMERIC);
			preparedStatement.setInt		(	7, regularReadingOfChildElectricityMeter.getRegularReadingOfChildElectricityMeterID());
			
			rowsAffected = preparedStatement.executeUpdate();
			
			
			if (rowsAffected == 1)
			{
				logger.info("Update sucessful: " + preparedStatement.toString());
				return rowsAffected;
			}
			else
			{
				logger.error("Update was unsuccesful: " + preparedStatement.toString());
				return WARNING_NO_ROWS_AFFECTED;
			}
		}
		catch (SQLException e) 
		{
			logger.error(e.getMessage());
			return WARNING_NO_ROWS_AFFECTED;		
		}
		finally
		{
			ConnectionManager.getInstance().closeStatement(preparedStatement);
			ConnectionManager.getInstance().closeResultSet(resultSet);
		}
	}

	@Override
	public int deleteRegularReadingOfChildElectricityMeter(
			int regularReadingOfChildElectricityMeterID) 
	{
		resultSet = null;
		rowsAffected = WARNING_NO_ROWS_AFFECTED;
		sql = "DELETE FROM Regular_readings_of_child_electricity_meter WHERE regularReadingOfChildElectricityMeterID = ?;";
		
		try 
		{
			preparedStatement = dbConnection.prepareStatement(sql);
			preparedStatement.setInt(1, regularReadingOfChildElectricityMeterID);
			rowsAffected = preparedStatement.executeUpdate();
			
			
			if (rowsAffected == 1)
			{
				logger.info("Deletion successful: " + preparedStatement.toString());
				return rowsAffected;
			}
			else
			{
				logger.info("Deletion unsuccessful: " + preparedStatement.toString());
				return WARNING_NO_ROWS_AFFECTED;
			}
		}
		catch(SQLException e) 
		{
			e.printStackTrace();
			return WARNING_NO_ROWS_AFFECTED;
		}
		finally
		{
			ConnectionManager.getInstance().closeStatement(preparedStatement);
			ConnectionManager.getInstance().closeResultSet(resultSet);
		}
	}
	
//-----------------END OF BASIC CRUD-----------------------------------

	@Override
	public List<RegularReadingOfChildElectricityMeter> getAllRegularReadingsOfChildElectricityMeters() 
	{
		List<RegularReadingOfChildElectricityMeter> listOfRegularReadingsOfChildElectricityMeters = 
				new ArrayList<RegularReadingOfChildElectricityMeter>();
		RegularReadingOfChildElectricityMeter regularReadingOfChildElectricityMeterRetrieved = null;
		sql = "SELECT * FROM Regular_readings_of_child_electricity_meter;";
		
		try 
		{
			preparedStatement = dbConnection.prepareStatement(
					sql,
					ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY
				);
			
			logger.info(preparedStatement.toString());
			resultSet = preparedStatement.executeQuery();
			//place the cursor at the beginning of the result set. Otherwise it can not start reading the result set. 
			resultSet.beforeFirst();
			
			while (resultSet.next())
			{	
				regularReadingOfChildElectricityMeterRetrieved = new RegularReadingOfChildElectricityMeter();
				regularReadingOfChildElectricityMeterRetrieved.setRegularReadingOfChildElectricityMeterID(resultSet.getInt("regularReadingOfChildElectricityMeterID"));
				regularReadingOfChildElectricityMeterRetrieved.setRegularReadingOfParentElectricityMeterFK(resultSet.getInt("regularReadingOfParentElectricityMeterFK"));
				regularReadingOfChildElectricityMeterRetrieved.setChildElectricityMeterFK(resultSet.getInt("childElectricityMeterFK"));
				regularReadingOfChildElectricityMeterRetrieved.setDateChildElectricityMeterReadingWasTaken(resultSet.getDate("dateChildElectricityMeterReadingWasTaken"));
				regularReadingOfChildElectricityMeterRetrieved.setChildElectricityMeterDaytimeReading(resultSet.getBigDecimal("childElectricityMeterDaytimeReading"));
				regularReadingOfChildElectricityMeterRetrieved.setChildElectricityMeterNightTimeReading(resultSet.getBigDecimal("childElectricityMeterNightTimeReading"));
				regularReadingOfChildElectricityMeterRetrieved.setChildElectricityMeterReactivePowerReading((BigDecimal) resultSet.getObject("childElectricityMeterReactivePowerReading"));
			
				listOfRegularReadingsOfChildElectricityMeters.add(regularReadingOfChildElectricityMeterRetrieved);
			}
		} 
		catch (SQLException e) 
		{
			logger.error(e.getMessage());
		}
		finally
		{
			ConnectionManager.getInstance().closeStatement(preparedStatement);
			ConnectionManager.getInstance().closeResultSet(resultSet);
		}
		
		return listOfRegularReadingsOfChildElectricityMeters;
	
	}
	
}

